package 树.middle;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author Lw中
 * @date 2020/10/27 12:19
 */
public class YiLingEr {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            val = x;
        }
    }

    /**
     * 二叉树的层序遍历
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        /* 创建存储list的集合 */
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        /* 创建队列用于二叉树的遍历 */
        Queue<TreeNode> queue = new LinkedList<>();
        /* 将根节点放入对列中 */
        queue.offer(root);
        /* 循环体中遍历二叉树 */
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 1; i <= size; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            lists.add(list);
        }
        return lists;
    }

}
